/*
 * 
 */
package es.drOsu.game;

import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.openfeint.api.OpenFeint;
import com.openfeint.api.resource.Achievement;
import com.openfeint.api.resource.Leaderboard;
import com.openfeint.api.resource.Score;

import es.drOsu.common.Constants;
import es.drOsu.common.SongsSQLiteHelper;

// TODO: Auto-generated Javadoc
/**
 * The Class Scores pantalla donde se visualiza todas las estadisticas y puntuaciones conseguidas nada mas terminar de jugar un jugador una cancion.
 */
public class Scores extends Activity implements OnClickListener{
	
	/** The Constant TAG sirve para el depurado y el LogCat. */
	private static final String TAG = "Scores";
	
	/** The path ruta de acceso a la cancion. */
	private String path;
	
	/** The game mode modo de juego elegido por el jugador. */
	private int gameMode;
	
	/** The game mode dificultad elegida por el jugador. */
	private int gameDifficulty;
	
	/** The user nombre del jugador. */
	private String user;
	
	/** The score puntuacion total conseguida. */
	private int score;
	
	/** The combo numero de acietos consecutivos conseguidos. */
	private int combo;
	
	/** The duration duracion de la cancion jugada. */
	private int duration;
	
	/** The min guardara el valor de la duracion(milisegundo) en minutos. */
	private double min;
	
	/** The check valor de control para el onResume(). */
	private boolean check = false;
	
	/** The ctx contexto de la activdad. */
	private Context ctx;
	
	/** The m location manager guarda la informacion sobre el manejador de localizacion. */
	private LocationManager mLocationManager;
	
	/** The m location listener pone a la escucha de nuevas localizaciones. */
	private MyLocationListener mLocationListener;

	/** The location guarda la localizacion del jugador. */
	private Location location;
	
	/** The loc guarda la provincia y el pais del jugador. */
	private String loc = " ";

	/** The shared variable de control para no cerrar el tablon si se comprate puntuacio. */
	private boolean shared = false;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
	    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
	    setContentView(R.layout.scores);
	    ctx=this;
	    Typeface face=Typeface.createFromAsset(getAssets(), "fonts/BILLD.TTF");
	    
	    Bundle bundle = this.getIntent().getExtras();
	    
	    score = bundle.getInt(Constants.keyScore);
	    combo = bundle.getInt(Constants.keyMaxCombo);
	    TextView totalScoreTextView = (TextView) findViewById(R.id.text_view_total_score);
	    totalScoreTextView.setText(getResources().getString(R.string.total_score_text).toString()+bundle.getInt(Constants.keyScore));
	    TextView maxComboTextView = (TextView) findViewById(R.id.text_view_max_combo);
	    maxComboTextView.setText(getResources().getString(R.string.max_combo_text).toString()+bundle.getInt(Constants.keyMaxCombo));
	    TextView hit50TextView = (TextView) findViewById(R.id.text_view_hit50);
	    hit50TextView.setText(""+bundle.getInt(Constants.keyHit50));
	    TextView hit100TextView = (TextView) findViewById(R.id.text_view_hit100);
	    hit100TextView.setText(""+bundle.getInt(Constants.keyHit100));
	    TextView bonusHit100TextView = (TextView) findViewById(R.id.text_view_bonushit100);
	    bonusHit100TextView.setText(""+bundle.getInt(Constants.keyBonusHit100));
	    TextView hit300TextView = (TextView) findViewById(R.id.text_view_hit300);
	    hit300TextView.setText(""+bundle.getInt(Constants.keyHit300));
	    TextView bonusHit300TextView = (TextView) findViewById(R.id.text_view_bonushit300);
	    bonusHit300TextView.setText(""+bundle.getInt(Constants.keyBonusHit300));
	    TextView beatHit300TextView = (TextView) findViewById(R.id.text_view_beathit300);
	    beatHit300TextView.setText(""+bundle.getInt(Constants.keyBeatHit300));
	    TextView failTextView = (TextView) findViewById(R.id.text_view_fail);
	    failTextView.setText(""+bundle.getInt(Constants.keyFail));
	    
	    Button retryButton = (Button) findViewById(R.id.Button_retry);
	    retryButton.setTypeface(face);
	    retryButton.setOnClickListener(this);
	    
	    Button continueButton = (Button) findViewById(R.id.Button_continue);
	    continueButton.setTypeface(face);
	    continueButton.setOnClickListener(this);
	    
	    Button shareButton = (Button) findViewById(R.id.Button_share);
	    shareButton.setTypeface(face);
	    shareButton.setOnClickListener(this);
	    
	    Button mainButton = (Button) findViewById(R.id.Button_main);
	    mainButton.setTypeface(face);
	    mainButton.setOnClickListener(this);
	    
	    path=bundle.getString(Constants.keyPath);
	    gameMode=bundle.getInt(Constants.keyGameMode);
	    gameDifficulty=bundle.getInt(Constants.keyGameDifficulty);
	    user=bundle.getString(Constants.keyUser);
	    duration=bundle.getInt(Constants.keyDuration);
	    
	    if(score>SongsSQLiteHelper.getScoreSongs(this, user, path)){
	    	SongsSQLiteHelper.updateSong(this, path, user, score);
	    	Toast.makeText(getBaseContext(), this.getResources().getString(R.string.new_record_score), Toast.LENGTH_SHORT).show();
	    }
	    //achievements

		SharedPreferences prefs = getSharedPreferences(user,Context.MODE_PRIVATE);
		if(!prefs.contains(Constants.sharedPreferencesFirstSongPlayed)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesFirstSongPlayed, Constants.sharedPreferencesFirstSongPlayedCheck);
			editor.commit();
			activateAchievement(Constants.achievementFirstSongPlayed);
		}
		if(score>=10000 && !prefs.contains(Constants.sharedPreferencesSuperStart)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesSuperStart, Constants.sharedPreferencesSuperStartCheck);
			editor.commit();
			activateAchievement(Constants.achievementSuperStar);
		}
		if(score>=20000 && !prefs.contains(Constants.sharedPreferencesDiva)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesDiva, Constants.sharedPreferencesDivaCheck);
			editor.commit();
			activateAchievement(Constants.achievementDiva);
		}
		if(score>=100000 && !prefs.contains(Constants.sharedPreferencesBeatMaster)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesBeatMaster, Constants.sharedPreferencesBeatMasterCheck);
			editor.commit();
			activateAchievement(Constants.achievementBeatMaster);
		}
		if(combo>=50 && !prefs.contains(Constants.sharedPreferencesComboStar)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesComboStar, Constants.sharedPreferencesComboStarCheck);
			editor.commit();
			activateAchievement(Constants.achievementComboStar);
		}
		if(combo>=75 && !prefs.contains(Constants.sharedPreferencesComboMaster)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesComboMaster, Constants.sharedPreferencesComboMasterCheck);
			editor.commit();
			activateAchievement(Constants.achievementComboMaster);
		}
		if(combo>=100 && !prefs.contains(Constants.sharedPreferencesComboProPlayer)){
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(Constants.sharedPreferencesComboProPlayer, Constants.sharedPreferencesComboProPlayercheck);
			editor.commit();
			activateAchievement(Constants.achievementComboProPlayer);
		}
	    //leaderboards
	    min = duration/60/1000;
	    Log.d(TAG, "min: "+min);
	    if(min>=6 && gameMode==Constants.HARDCORE){
	    	saveScoreInLeaderboard(Constants.leaderboardHardcoreChampionPlus,score);
	    }else{
		    if(min>=5 && gameMode==Constants.HARDCORE){
		    	saveScoreInLeaderboard(Constants.leaderboardHardcoreChampion5,score);
		    }else {
		    	if(min>=4 && gameMode==Constants.HARDCORE){
			    	saveScoreInLeaderboard(Constants.leaderboardHardcoreChampion4,score);
			    }else{
			    	if(min>=3 && gameMode==Constants.HARDCORE){
				    	saveScoreInLeaderboard(Constants.leaderboardHardcoreChampion3,score);
				    }else
				    	saveScoreInLeaderboard(Constants.leaderboardHardcoreChampion2,score);
			    }
		    }
	    }	    
	}
	
	 /**
 	 * Activate achievement sirve para desbloquear los logros conseguidos por el jugador en Open Feint.
 	 *
 	 * @param achievementID the achievement id codigo de identificacion para saber que logro se ha de activar
 	 */
 	private void activateAchievement(String achievementID) {
		 new Achievement(achievementID).unlock(new Achievement.UnlockCB() {
				@Override public void onSuccess(boolean newUnlock) {
					Scores.this.setResult(Activity.RESULT_OK);					
				}
				@Override public void onFailure(String exceptionMessage) {
					Toast.makeText( Scores.this,
						"Error (" + exceptionMessage + ") unlocking achievement.",
						Toast.LENGTH_SHORT).show();
					Scores.this.setResult(Activity.RESULT_CANCELED);
				}
		});
		
	}

	/**
	 * Save score in leaderboard guarda la nueva puntuacion conseguida en el tablon de puntuaciones de Open Feint.
	 *
	 * @param leaderboard the leaderboard codigo de identificacion para saber que tablon es el que hay poner dicha puntuacion
	 * @param score the score puntuacion a guardar en dicho tablon de puntuaciones
	 */
	private void saveScoreInLeaderboard(String leaderboard,
			int score) {
		 Score s = new Score(score, null); // Second parameter is null to indicate that custom display text is not used.
		 Leaderboard l = new Leaderboard(leaderboard);
		 Log.d(TAG, "score= "+score+" leaderboard: "+leaderboard);
		 s.submitTo(l, new Score.SubmitToCB() {
		 	@Override public void onSuccess(boolean newHighScore) {
		 		// sweet, score was posted
		 		Scores.this.setResult(Activity.RESULT_OK);
		 		
		 	}

		 	@Override public void onFailure(String exceptionMessage) {
		 		Toast.makeText(Scores.this,
		 		"Error (" + exceptionMessage + ") posting score.",
		 		Toast.LENGTH_SHORT).show();
		 		Scores.this.setResult(Activity.RESULT_CANCELED);
		 	}
		 });

		
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View v){
		 Bundle newBundle =  new Bundle();
		 newBundle.putString(Constants.keyUser, user);
	 	 newBundle.putInt(Constants.keyGameMode, gameMode);
	 	 newBundle.putInt(Constants.keyGameDifficulty, gameDifficulty);
		 
		 switch (v.getId()){
		 case(R.id.Button_main):
			 Intent intentMain = new Intent(this,DrosuMain.class);
		 	 startActivity(intentMain);
			 break;
		 case(R.id.Button_retry):
			 Intent intentNewGame = new Intent(this,GameNewActivity.class);
		 	 newBundle.putString(Constants.keyPath, path);
		 	 intentNewGame.putExtras(newBundle);
 			 startActivity(intentNewGame);
			 break;
		 case(R.id.Button_continue):
			 Intent intentGame = new Intent(this,Game.class);
			 intentGame.putExtras(newBundle);
		 	 startActivity(intentGame);
			 break;
		 case(R.id.Button_share):
			 mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);				
			//mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
			//Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
				Log.d(TAG, "si esta activo GPS");
				mLocationListener = new MyLocationListener();
				mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
				location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
			}else{
				if(mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
					Log.d(TAG, "si esta activo network");
					mLocationListener = new MyLocationListener();
					mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
					location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				}else{
					Toast.makeText(getBaseContext(), 
			                   getResources().getString(R.string.error_no_location), 
			                   Toast.LENGTH_LONG).show();
					loc=null;
				}
			}
			 check=true;
			 es.drOsu.common.Song song=new es.drOsu.common.Song(path);
			 shared =true;
			 //Social.share(this, "drOsu", user+" "+this.getResources().getString(R.string.share1)+" "+song.title+" - "+song.artist+": "+score+" location: "+loc);
			 break;
		 }
		
	 }

	/* (non-Javadoc)
	 * @see android.app.Activity#onRestart()
	 */
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		if(shared)
			shared=false;
		if(check==false)
			finish();
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		
		super.onPause();
		if(!shared)
			finish();
	}

	/**
	 * The listener interface for receiving myLocation events.
	 * The class that is interested in processing a myLocation
	 * event implements this interface, and the object created
	 * with that class is registered with a component using the
	 * component's <code>addMyLocationListener<code> method. When
	 * the myLocation event occurs, that object's appropriate
	 * method is invoked.
	 *
	 * @see MyLocationEvent
	 */
	private class MyLocationListener implements LocationListener 
    {
        
        /* (non-Javadoc)
         * @see android.location.LocationListener#onLocationChanged(android.location.Location)
         */
        @Override
		public void onLocationChanged(Location location) {
        	Log.d(TAG, "location on changed"+location);
        	loc = "";
			/*loc = "";
	        loc += "Time: "        + location.getTime() + "\n";
	        loc += "\tLatitude:  " + location.getLatitude()  + "\n";
	        loc += "\tLongitude: " + location.getLongitude() + "\n";
	        loc += "\tAccuracy:  " + location.getAccuracy()  + "\n";*/
	        /*s += location.getProvider();
	        s += location.toString();
	        s += location.getExtras();
	        s += location.toString();
	        */
	       
	        Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	        try {
	           List<Address> addresses = geoCoder.getFromLocation(location.getLatitude(),
	                   location.getLongitude(), 1);
	           //loc = " ";
	           loc +=addresses.get(0).getSubAdminArea();
	           loc +=" ";
	           loc +=addresses.get(0).getCountryName();
	           
	           //loc +=addresses.get(0).getLocality();
	           handler.sendEmptyMessage(0);
	        }catch(Exception e){
	            e.getMessage();
	        }
		}

		/* (non-Javadoc)
		 * @see android.location.LocationListener#onProviderDisabled(java.lang.String)
		 */
		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		/* (non-Javadoc)
		 * @see android.location.LocationListener#onProviderEnabled(java.lang.String)
		 */
		@Override
		public void onProviderEnabled(String arg0) {
		}

		/* (non-Javadoc)
		 * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
		 */
		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			
		}
    }
	
	/** The handler manejador para saber si ya se ha conseguido una lectura de la localizacion del jugador. */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			
			mLocationManager.removeUpdates(mLocationListener);
			es.drOsu.common.Song song=new es.drOsu.common.Song(path);
			if(gameDifficulty==Constants.EASY)
				Social.share(ctx, "drOsu", OpenFeint.getCurrentUser().name +" "+ctx.getResources().getString(R.string.share1)+" "+song.title+" - "+song.artist+" "+ctx.getResources().getString(R.string.share2)+" "+ctx.getResources().getString(R.string.easy_mode_label)+": "+score+" "+ctx.getResources().getString(R.string.share3)+loc);
			if(gameDifficulty==Constants.MEDIUM)
				Social.share(ctx, "drOsu", OpenFeint.getCurrentUser().name +" "+ctx.getResources().getString(R.string.share1)+" "+song.title+" - "+song.artist+" "+ctx.getResources().getString(R.string.share2)+" "+ctx.getResources().getString(R.string.medium_mode_label)+": "+score+" "+ctx.getResources().getString(R.string.share3)+loc);
			if(gameDifficulty==Constants.CHAMPION)
				Social.share(ctx, "drOsu", OpenFeint.getCurrentUser().name +" "+ctx.getResources().getString(R.string.share1)+" "+song.title+" - "+song.artist+" "+ctx.getResources().getString(R.string.share2)+" "+ctx.getResources().getString(R.string.champion_mode_label)+": "+score+" "+ctx.getResources().getString(R.string.share3)+loc);
	    	/*if (loc!=null) {
	    		Toast.makeText(getBaseContext(), 
		                   loc, 
		                   Toast.LENGTH_LONG).show();
	    	}*/
		}
	};
}
